package com.itheima.reggie.controller;

import com.github.pagehelper.PageHelper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.entity.Page;
import com.itheima.reggie.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/employee")
@Slf4j
public class EmployeeController {
    @Autowired(required = false)
    private EmployeeService employeeService;

    @PostMapping("/login")
    public R<Employee> login(@RequestBody Employee employee, HttpSession session){
//        把参数传给service
        R<Employee> result = employeeService.login(employee);
//        判断结果的编码是否等于1，如果是则创建session来保存id值
        if(result.getCode()==1){
            session.setAttribute("employee",result.getData().getId());
        }
        return result;
    }
    @PostMapping("/logout")
    public R<String> logout(HttpSession session){
        session.invalidate();
        return R.success("退出成功");

    }
    //添加员工信息
    @PostMapping//在后端的界面并没有这个后面的路径，所以不用加
    public R<String> save(@RequestBody Employee employee,HttpSession session){
        Long id = (Long) session.getAttribute("employee");
        employee.setCreateUser(id);
        employee.setUpdateUser(id);
        employeeService.save(employee);
        return R.success("保存成功！");
    }
//    分页操作
    @GetMapping("/page")//在后端的界面并没有这个后面的路径，所以不用加
    public R<Page<Employee>> findByName(Integer page,Integer pageSize,String name){

        Page<Employee> pages=employeeService.findByName(page,pageSize,name);
        return R.success(pages);
    }
    //修改禁用状态
    @PutMapping
    public R<String> update(@RequestBody Employee employee,HttpSession session){
        Long empId = (Long) session.getAttribute("employee");
        employee.setUpdateUser(empId);
        employeeService.update(employee);
        return R.success("修改成功！");

    }
    //通过id来查询
    @GetMapping("/{id}")
    public R<Employee> findById(@PathVariable Integer id){
        R<Employee> result=employeeService.findById(id);
        return result;

    }


}
